package com.colorlight.cloud.complete.entity.instructions;

import com.colorlight.cloud.common.exception.ParameterException;
import com.colorlight.cloud.common.model.ExceptionEnum;
import com.colorlight.cloud.complete.api.CompleteEntityScheduleActions;
import com.colorlight.cloud.complete.entity.po.TestMode;
import com.colorlight.iot.proto.complete.instruction.CompleteInstruction;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 设置测试模式
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Slf4j
public class SetTestModel implements CompleteEntityScheduleActions {

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class InputMsg implements Serializable {
        /**
         * 测试模式
         */
        private List<TestMode> testModel;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class OutputMsg implements Serializable {
        /**
         * 测试模式
         */
        private List<TestMode> testModel;
    }

    private InputMsg inputMsg;
    private OutputMsg outputMsg;

    @Override
    public ByteString objectConvertBytes() {
        final CompleteInstruction.SetTestModel.InputMsg.Builder inputMsgBuilder =
                CompleteInstruction.SetTestModel.InputMsg.newBuilder();
        SetTestModel.InputMsg thisInput = this.getInputMsg();
        inputMsgBuilder.addAllTestModel(thisInput.getTestModel().stream().map(TestMode::toProto).collect(Collectors.toList()));

        final CompleteInstruction.SetTestModel.Builder builder =
                CompleteInstruction.SetTestModel.newBuilder();
        builder.setInput(inputMsgBuilder);
        return builder.build().toByteString();
    }

    @Override
    public SetTestModel byteConvertObject(ByteString bytes) {
        CompleteInstruction.SetTestModel setTestModel = null;
        try {
            setTestModel = CompleteInstruction.SetTestModel.parseFrom(bytes);
        } catch (InvalidProtocolBufferException e) {
            log.error("", e);
        }
        if (Objects.isNull(setTestModel)) {
            throw new ParameterException(ExceptionEnum.MSG_PARAMETER_EXCEPTION);
        }
        SetTestModel.OutputMsg outputMsg = new SetTestModel.OutputMsg();
        CompleteInstruction.SetTestModel.OutputMsg output = setTestModel.getOutput();
        List<TestMode> collect = output.getTestModelList().stream().map(e -> new TestMode().formProto(e)).collect(Collectors.toList());
        outputMsg.setTestModel(collect);
        this.setOutputMsg(outputMsg);
        return this;
    }
}

